package com.ldj.security.config;

import com.ldj.security.service.CustomUserService;
import com.sun.org.apache.xpath.internal.operations.String;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.MessageDigestPasswordEncoder;

/**
 * Created with IntelliJ IDEA.
 * User: Lv.Dongjie
 * Date: 2018/5/22
 * Time: 18:46
 * Description:
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启security注解
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserService customUserService;

    @Bean
    public LoginSuccessHandler loginSuccessHandler(){
        return new LoginSuccessHandler();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService).passwordEncoder(new MessageDigestPasswordEncoder("MD5"));
       /*auth.inMemoryAuthentication()
                .withUser("ldj").password("123456").roles("USER");*/
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        System.out.println(1);
        http
                .csrf().disable()
                .authorizeRequests()
                .anyRequest().authenticated() // 所有请求页面都需要登录才能访问
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll() // 定制登录行为,登录页面可以任意访问
                .successHandler(loginSuccessHandler())
                .defaultSuccessUrl("/home")
                //.successHandler(loginSuccessHandler())
                .loginProcessingUrl("/tologin")  // 自定义的登录接口
                .failureForwardUrl("/errorp")
                .and()
                .logout().permitAll(); // 定制注销行为,注销请求可以任意访问
    }


}
